<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/2/12
 * Time: 11:59
 */

namespace App\HttpController\Admin;


use App\Model\AdminsModel;
use App\Model\AdminsOpenidModel;
use App\Model\CategorysModel;
use App\Model\TmplmsgsModel;
use App\Model\VideosDaduizhangModel;
use App\Utility\Cache;
use App\Utility\MiniProgram;
use Carbon\Carbon;

class VideoController extends AuthController
{
    /**
     * 视频管理_列表
     */
    public function index(){
        $request = $this->request();
        $page = (int)$request->getRequestParam('page')??1;
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$applet){
            return $this->writeJson(1, null,'applet参数错误');
        }
        $sort = $request->getRequestParam('sort')??0;
        switch ($sort) {
            case 1:
                $sort = 'view';
                break;
            case 2:
                $sort = 'share';
                break;
            default:
                $sort = 'id';
                break;
        }

        $where = [
            'title' => (string)$request->getRequestParam('name')??'',
            'chanel_id' => (int)$request->getRequestParam('chanel_id')??0,
            'option' => (int)$request->getRequestParam('option')??0,
            'banner' => (int)$request->getRequestParam('banner')??0,
            'status' => (int)$request->getRequestParam('status')??0,
            'userid' => (int)$request->getRequestParam('admins')??0,
            'start' => $request->getRequestParam('start')??'',
            'end' => $request->getRequestParam('end')??'',
        ];
        $appletModel = $this->appletVideoModel($applet);
        $videoModel = new $appletModel;
//        $videoModel = new VideosDaduizhangModel();

        if($where['title']){
            $videoModel->where('title','%'.$where['title'].'%','like');
        }
        if($where['chanel_id'] > 0){
            $videoModel->where('chanel_id',$where['chanel_id']);
        }
        if($where['option'] > 0){
            $videoModel->where('`option`',$where['option']);
        }
        if($where['banner'] > 0){
            $videoModel->where('banner',$where['banner']);
        }
        if($where['status'] > 0){
            $videoModel->where('videos_'.$applet.'.status',$where['status']);
        }
        if($where['userid']){
            $videoModel->where('videos_'.$applet.'.userid',$where['userid']);
        }
        if($where['start']){
            $videoModel->where('videos_'.$applet.'.created_at',$where['start'],'>=');
        }
        if($where['end']){
            $videoModel->where('videos_'.$applet.'.created_at',$where['end'].' 23:59:59','<=');
        }
        $videoModel->select('admins.nickname,videos_'.$applet.'.*')->join('admins','videos_'.$applet.'.userid = admins.id','LEFT');
        $videoModel->orderBy($sort, 'DESC');
        $list = $videoModel->paginate($page);
        foreach ($list['data'] as $key => &$item){
            $item['pre'] = $item['share'] ? round((($item['share']/$item['view'])*10000)/100,2).'%' : '0%';
        }
        $this->stateToText($list['data'], [
            'status' => VideosDaduizhangModel::STATUS_TEXT,
            'option' => VideosDaduizhangModel::OPTION_TEXT,
            'banner' => VideosDaduizhangModel::BANNER_TEXT,
        ]);

        // 统计
        $videoCount = new $appletModel;
        if($where['title']){
            $videoCount->where('title',$where['title']);
        }
        if($where['chanel_id'] > 0){
            $videoCount->where('chanel_id',$where['chanel_id']);
        }
        if($where['option'] > 0){
            $videoCount->where('`option`',$where['option']);
        }
        if($where['banner'] > 0){
            $videoCount->where('banner',$where['banner']);
        }
        if($where['status'] > 0){
            $videoCount->where('status',$where['status']);
        }
        if($where['userid']){
            $videoCount->where('userid',$where['userid']);
        }
        if($where['start']){
            $videoCount->where('created_at',$where['start'],'>=');
        }
        if($where['end']){
            $videoCount->where('created_at',$where['end'],'<=');
        }
        $videoCount->get();
        $msg['count']['share'] = $videoCount->sum('share');
        $msg['count']['view'] = $videoCount->sum('view');
        $adminsModel = new AdminsModel();
        $msg['admins'] = $adminsModel->select('id,nickname')->get();
        return $this->writeJson(0,$list,$msg);
    }

    /**
     * 视频管理_更新
     */
    public function update(){
        $request = $this->request();
        $params = $request->getRequestParam();
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$applet){
            return $this->writeJson(1, null,'applet参数错误');
        }
        if(mb_strlen($params['link']) !== 11){
            $vid = self::getVideo($params['link']);
            if (!$vid) {
                return $this->writeJson(1, null,'视频链接有误');
            }
        }

        $params['userid'] = $this->userid;
        $appletModel = $this->appletVideoModel($applet);
        $videoModel = new $appletModel;
//        $videoModel = new VideosDaduizhangModel();
        if(isset($params['id']) && (int)$params['id'] > 0){
            //编辑
            $info = $videoModel->find($params['id']);
            if (!$info) {
                return $this->writeJson(1, null,'数据不存在');
            }

            unset($params['userid']);
            $params['updated_at'] = Carbon::now();
            $isUpdate = $videoModel->update($params);
            if(!$isUpdate){
                return $this->writeJson(1, null,'系统错误');
            }
            return $this->writeJson(0, null,'编辑视频信息成功');
        }
        //新增
        if(isset($params['id'])){
            unset($params['id']);
        }
        //判断数据是否存在，去重（标题&链接ID）
        $videoModel->where('title',$params['title']);
        if(mb_strlen($params['link']) !== 11){
            $videoModel->where('link','%'.$vid.'%','like','or');
        }else{
            $videoModel->where('link','%'.$params['link'].'%','like','or');
        }
        $is_video = $videoModel->first();
        if($is_video){
            return $this->writeJson(1, null,'该视频已经存在！');
        }
        $catesModel = new CategorysModel();
        $catesOne = $catesModel->where('type',1)->inRandomOrder()->first();
        $params['cateid'] = $catesOne['id'];
        $params['view'] = 0;
        $params['share'] = 0;
        $params['created_at'] = Carbon::now();
        $params['updated_at'] = $params['created_at'];
        $isSave = $videoModel->create($params);
        if(!$isSave){
            return $this->writeJson(1, null,'系统错误');
        }
        return $this->writeJson(0, $params);
    }
    /**
     * 解析视频地址
     */
    protected function getVideo($url){
        //获取腾讯视频真实地址
        if (strstr($url, 'v.qq.com')) {
            //匹配腾讯链接拿到所需的vid
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $url, $matchs);
            if ($result) {
                return $matchs[1][0];
            }
        }
        return false;
    }

    /**
     * 删除
     * @return bool
     * @throws \Throwable
     */
    public function destroy(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$id){
            return $this->writeJson(1, null,'参数错误');
        }
        if(!$applet){
            return $this->writeJson(1, null,'applet参数错误');
        }
        $appletModel = $this->appletVideoModel($applet);
        $model = new $appletModel;
        if(is_array($id)){
            $model->whereIn('id',$id)->delete();
        }else{
            $model->destroy($id);
        }
        return $this->writeJson(0);
    }


    /**
     * 统计分析
     */
    public function count(){
        $request = $this->request();
        $params = $request->getRequestParam();
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$applet){
            return $this->writeJson(1, null,'applet参数错误');
        }
        $appletModel = $this->appletCountModel($applet);
        $countModel = new $appletModel;
        if(!isset($params['start'])){
            $params['start'] = Carbon::now()->subDays(31)->toDateString();
        }

        $lists = $countModel->where('date',$params['start'],'>=')
            ->where(function ($query) use($params){
                if(isset($params['id']) && (int)$params['id'] > 1){
                    $query->where('admin_id',$params['id']);
                }
                if(isset($params['end']) && $params['end']){
                    $query->where('date',$params['end'],'<=');
                }
            })->select('sum(views) as views, sum(share_in) as share_in,date')
            ->groupBy('date')
            ->orderBy('date','ASC')
            ->get();
        return $this->writeJson(0,$lists);
    }

    /**
     * 更新状态
     * @return bool
     */
    public function updateStatus(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $applet = $request->getRequestParam('applet') ?? '';
        if(!$applet){
            return $this->writeJson(1, null, 'applet参数错误！');
        }
        if(!isset($data['id']) || !$data['id']){
            return $this->writeJson(1, null, 'id参数错误！');
        }
        $appletModel = $this->appletVideoModel($applet);
        $model = new $appletModel;
        //修改
        $isUpdate = $model->update($data);
        if($isUpdate){
            return $this->writeJson(0,null,'更新成功');
        }else{
            return $this->writeJson(1,null,'更新失败，稍后重试');
        }

    }

    /**
     * 模板推送，手机预览
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\OrderByFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function preview(){
        $request = $this->request();
        $id = $request->getRequestParam('id') ?: 0;
        $applet = $request->getRequestParam('applet') ?? '';

        if(empty($id) || !$applet){
            return $this->writeJson(1,null,'参数错误！');
        }
        $configAppletName = $this->appletConfigModel($applet);
        $configModel = new $configAppletName;
        $template_id = $configModel->where('name','template_id')->first();
        if(!$template_id){
            return $this->writeJson(1,null,'请【配置管理】添加template_id');
        }
        //获取用户openID
        $adminOpenid = (new AdminsOpenidModel())->getAdminOpenid($applet,$this->userid);
        if(!$adminOpenid){
            return $this->writeJson(1,null,'请联系技术人员添加openID！');
        }
        $appletAritcleName = $this->appletVideoModel($applet);
        $articleModel = new $appletAritcleName;
        $articlesInfo = $articleModel->find($id);

        if($articlesInfo['is_link'] == 2){
            $prama = 'url='.$articlesInfo['link_url'];
        }else{
            $prama = 'id='.$id;
        }
        $model = new TmplmsgsModel();
        $msg = $model->where('template_id',$template_id['value'])->first();
        $page = $msg['page'].'?'.$prama;

//        Logger::getInstance()->log('$user:\n'.json_encode($user),'user-test');
        //判断是否有可以formId
        $cache =  new Cache();
        //根据openid取找到相应的openid的formid的集合，先删除该集合已过期的所有的formid,
        $cache->zRemRangeByScore($adminOpenid,0,time()+10);
        //然后取一个formid的值
        $formid_array = $cache->zRange($adminOpenid,0,0);
//        Logger::getInstance()->log('formid_array:'.PHP_EOL.json_encode($formid_array),'user-test');
        if(count($formid_array) == 0){
            return $this->writeJson(1,null,'没有可用的FORMID了！');
        }
        $formid = $formid_array[0];
        $appletModel = $this->appletVideoModel($applet);
        $ArticlesMeiwenModel = new $appletModel;
        $articlesInfo = $ArticlesMeiwenModel->select('id,title')->find($id);
        $msg['keywords'][0]->keyword2 = $articlesInfo['title'];
        $wechat = new MiniProgram($applet);
        $sendData = [
            'touser'      => $adminOpenid,
            'template_id' => $msg['template_id'],
            'page'        => $page,
            'form_id'     => $formid,
            'data'        => $msg['keywords'][0],
            'emphasis_keyword' => '',
        ];
        $result = $wechat->sendTemplateMessage($sendData);
        if($result['errcode'] == 0){
            //从集合中移除该formid
            $cache->zrem($adminOpenid,$formid);
            //如果删除集合中过期的formid值后该集合为空，则删除对应的小程序的openid集合中的openid元素
            if($cache->zCard($adminOpenid) == 0) $cache->srem($applet,$applet.'*'.$adminOpenid);
            return $this->writeJson(0, null, '推送成功');
        }else{
            if(($result['errcode'] == 41028) || ($result['errcode'] == 41029)){
                //从集合中移除该formid
                $cache->zrem($adminOpenid,$formid);
                //如果删除集合中过期的formid值后该集合为空，则删除对应的小程序的openid集合中的openid元素
                if($cache->zCard($adminOpenid) == 0) $cache->srem($applet,$applet.'*'.$adminOpenid);
            }
            return $this->writeJson(1, $result, '推送失败，'.$result['chmsg']);
        }

    }
}
